#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./login/bkaccount/views.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import urllib
from django.shortcuts import render
from django.http import JsonResponse, HttpResponseForbidden, HttpResponseRedirect, HttpResponse
from django.views.decorators.http import require_POST
from django.conf import settings
from django.db import transaction
from bkaccount.accounts import Account
from bkaccount.decorators import login_exempt
from bkaccount.models import BkUser
from bkaccount.utils import read_user_import_xls, write_excel, get_page_info
from bkaccount.validators import validate_password, validate_username, validate_twice_password, is_xls_valid, validate_chname, validate_qq, validate_phone, validate_email
from common.log import logger

@login_exempt
def login(request):
    """
    登入
    """
    account = Account()
    return account.login(request)


@login_exempt
def logout(request):
    """
    登出
    """
    account = Account()
    return account.logout(request)


def csrf_failure(request, reason=''):
    return HttpResponseForbidden(render(request, 'csrf_failure.html'), content_type='text/html')


def users(request):
    """
    用户管理页面
    """
    default_paasword = settings.PASSWORD
    error_msg = request.GET.get('error_msg', '')
    success_msg = request.GET.get('success_msg', '')
    context = {'default_paasword': default_paasword,
       'error_msg': error_msg,
       'success_msg': success_msg
       }
    return render(request, 'account/users.html', context)


def get_info(request):
    """
    查询用户信息
    """
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    page, page_size = get_page_info(page, page_size)
    search_username = '' if request.user.is_superuser else request.user.username
    search_data = request.GET.get('search_data').replace('&nbsp;', '').strip()
    search_role = request.GET.get('search_role')
    records = BkUser.objects.get_batch_user_with_paginator(page, page_size, search_username, search_data, search_role)
    adjacent_pages = 3
    start_page = max(records.number - adjacent_pages, 1)
    if start_page < adjacent_pages:
        start_page = 1
    end_page = records.number + adjacent_pages + 1
    if end_page > records.paginator.num_pages - adjacent_pages + 2:
        end_page = records.paginator.num_pages + 1
    page_numbers = [ n for n in range(start_page, end_page) ]
    show_first = 1 not in page_numbers
    show_last = records.paginator.num_pages not in page_numbers
    context = {'records': records,
       'page_numbers': page_numbers,
       'show_first': show_first,
       'show_last': show_last
       }
    return render(request, 'account/user_table.part', context)


@require_POST
def save_user(request):
    """
    添加、编辑用户信息
    """
    user_id = request.POST.get('user_id')
    username = request.POST.get('username').strip()
    chname = request.POST.get('chname').strip()
    qq = request.POST.get('qq').strip()
    phone = request.POST.get('phone').strip()
    email = request.POST.get('email').strip()
    role = request.POST.get('role')
    if user_id and not request.user.is_superuser and request.user.id != int(user_id) or not user_id and not request.user.is_superuser:
        return JsonResponse({'result': False,'msg': u'非管理员用户, 没有权限进行操作, 请找管理员申请权限!','data': ''})
    if not user_id:
        is_valid, msg = validate_username(username)
        if not is_valid:
            return JsonResponse({'result': False,'msg': msg,'data': user_id})
    if request.user.is_superuser:
        role = int(role) if 1 else -1
        result, user_id, msg = BkUser.objects.modify_or_create_user_by_userid(user_id, username, chname, qq, phone, email, role)
        return result or JsonResponse({'result': False,'msg': msg,'data': user_id})
    return JsonResponse({'result': True,'msg': u'保存用户信息成功','data': user_id})


@require_POST
def del_user(request):
    """
    删除用户
    必须保留一个管理员用户
    """
    if not request.user.is_superuser:
        return JsonResponse({'result': False,'msg': u'非管理员用户, 没有权限进行操作, 请找管理员申请权限!','data': ''})
    user_id = request.POST.get('user_id')
    username = request.POST.get('username')
    result, msg = BkUser.objects.delete_user(user_id, username)
    if not result:
        return JsonResponse({'result': False,'msg': msg})
    return JsonResponse({'result': True,'msg': u'用户(%s)删除成功' % username})


@require_POST
def change_password(request):
    user_id = request.POST.get('user_id', '')
    new_password1 = request.POST.get('new_password1', '').strip()
    new_password2 = request.POST.get('new_password2', '').strip()
    if not request.user.is_superuser and request.user.id != int(user_id):
        return JsonResponse({'result': False,'msg': u'非管理员用户, 没有权限进行操作, 请找管理员申请权限!','data': ''})
    is_valid, msg = validate_twice_password(new_password1, new_password2)
    if not is_valid:
        return JsonResponse({'result': False,'msg': msg,'data': ''})
    is_valid, msg = validate_password(new_password1)
    if not is_valid:
        return JsonResponse({'result': False,'msg': msg})
    result, msg = BkUser.objects.modify_password_by_userid(user_id, new_password1)
    if not result:
        return JsonResponse({'result': False,'msg': msg})
    return JsonResponse({'result': True,'msg': ''})


@require_POST
def import_data(request):
    """
    批量导入用户
    """
    error_msg = ''
    if not request.user.is_superuser:
        error_msg = u'非管理员用户, 没有权限进行操作, 请找管理员申请权限!'
        return HttpResponseRedirect('%saccounts/?error_msg=%s' % (settings.SITE_URL, error_msg))
    xls_file = request.FILES['data_files']
    is_valid, error_msg = is_xls_valid(xls_file.name)
    if not is_valid:
        param = urllib.urlencode({'error_msg': unicode(error_msg).encode('utf-8')})
        return HttpResponseRedirect(urllib.quote('%saccounts/?%s' % (settings.SITE_URL, param)))
    try:
        user_list = read_user_import_xls(xls_file)
    except:
        logger.exception(u'解析用户导入数据时出错')
        error_msg = u'文件解析出错，请下载 EXCEL模板文件 填写用户数据'
        return HttpResponseRedirect('%saccounts/?error_msg=%s' % (settings.SITE_URL, error_msg))

    try:
        with transaction.atomic():
            for _u in user_list:
                _username = _u['username']
                is_valid, error_msg = validate_username(_username)
                if not is_valid:
                    raise ValueError(error_msg)
                is_valid, error_msg = validate_chname(_u['chname'])
                if not is_valid:
                    raise ValueError(error_msg)
                is_valid, error_msg = validate_qq(_u['qq'])
                if not is_valid:
                    raise ValueError(error_msg)
                is_valid, error_msg = validate_phone(_u['phone'])
                if not is_valid:
                    raise ValueError(error_msg)
                is_valid, error_msg = validate_email(_u['email'])
                if not is_valid:
                    raise ValueError(error_msg)
                BkUser.objects.modify_or_create_user_by_username(_username, _u['chname'], _u['qq'], _u['phone'], _u['email'])

    except Exception as e:
        logger.error(e)
        error_msg = error_msg or u'用户导入出现异常%s' % e if 1 else error_msg

    redierct_url = '%saccounts/?success_msg=%s' % (settings.SITE_URL, u'用户导入成功')
    if error_msg:
        param = urllib.urlencode({'error_msg': unicode(error_msg).encode('utf-8')})
        redierct_url = '%saccounts/?%s' % (settings.SITE_URL, param)
    return HttpResponseRedirect(redierct_url)


def export_data(request):
    """
    以EXCEL的方式导出用户数据
    """
    response = HttpResponse()
    response['Content-Disposition'] = 'attachment; filename="bk_user_export.xls'
    head_list = [
     u'用户名', u'中文名', u'QQ', u'联系电话', u'常用邮箱', u'角色']
    records = []
    users = BkUser.objects.all().order_by('-id').order_by('-is_superuser')
    for _user in users:
        if _user.is_superuser:
            role = u'管理员' if 1 else u'用户'
            record = (
             _user.username, _user.chname, _user.qq, _user.phone, _user.email, role)
            records.append(record)

    is_success, error_msg, wbk = write_excel(head_list, records)
    if not is_success:
        logger.error(error_msg)
    wbk.save(response)
    return response
